package mess;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LeeCode_15_second {
    public static void main(String[] args) {
        int[] nums = new int[]{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,-1};
        System.out.println(threeSum(nums));
    }
    private static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        //1.排序
        Arrays.sort(nums);
        //2.双指针
        int len = nums.length;
        for (int i = 0; i < len - 2; i++) {
            if (nums[i] > 0 || (i > 0 && nums[i] == nums[i - 1] && nums[i] == 0))
                break;
            if (i > 0 && nums[i] == nums[i - 1])
                continue;
            int target = -nums[i];
            int j = i + 1;
            int k = len - 1;
            while (j < k){
                int sum2 = nums[j] + nums[k];
                if (sum2 > target)
                    k--;
                else if (sum2 < target)
                    j++;
                else {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[j]);
                    list.add(nums[k]);
                    result.add(list);
                    j++;
                    k--;
                    while (nums[j] == nums[j - 1] && j < len - 1)
                        j++;
                }
            }
        }
        return result;
    }
}
